#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author:zhangcong
# Email:zc_92@sina.com


from django.shortcuts import render, HttpResponse
from webadmin.views_dir import pub

from webadmin import models
from django.http import JsonResponse

from datetime import datetime

from webadmin.views_dir.mongo_oper import get_db_obj
import collections
import json
from bson.objectid import ObjectId


# 对开通权限进行排序, 并生成 jstree 对应的字典
def sort_rights_data(pid, result_data):

    rights_obj = get_db_obj().rights.find({"p_id": pid}, {"name": 1, "_id": 1, "p_id": 1})

    for obj in rights_obj:
        # 表示是最顶层
        if not obj["p_id"]:
            result_data[obj["_id"]] = {
                "name": obj["name"],
                "children": collections.OrderedDict()
            }
        else:
            result_data[obj["_id"]] = {
                "name": obj["name"],
                "children": collections.OrderedDict()
            }

        pid = obj["_id"]
        sort_rights_data(pid, result_data[obj["_id"]]["children"])

    return result_data


# 根据开通权限的字典信息生成开通权限前端 jstree 所需要的数据
def create_rights_html(rights_dict, rights_ids):

    return_html = []
    for k, v in rights_dict.items():
        temp_html = {
            "text": v["name"],
            "id": k,
            "state": {}
        }
        if str(k) in rights_ids:
            temp_html["state"]["selected"] = True

        if "children" in v and v["children"]:
            temp_html["state"]["opened"] = True
            temp_html["children"] = create_rights_html(v["children"], rights_ids)
        return_html.append(temp_html)
    return return_html


# 角色管理
@pub.is_login
def roles_management(request):
    if "pageNum" in request.POST:
        pageNum = int(request.POST.get("pageNum"))
    else:
        pageNum = 1

    if "numPerPage" in request.POST:
        numPerPage = int(request.POST.get("numPerPage"))
    else:
        numPerPage = 20

    roles_objs_all = get_db_obj().roles.find()
    count = roles_objs_all.count()
    roles_objs = roles_objs_all.skip(pageNum * numPerPage - numPerPage).limit(numPerPage)

    # 所有用户的信息
    user_data = {}
    for i in get_db_obj().user.find({}, {"_id": 1, "username": 1}):
        user_data[i["_id"]] = i["username"]

    return render(request, 'webadmin/roles/roles_management.html', locals())


@pub.is_login
def roles_management_oper(request, oper_type, o_id):

    user_id = request.session['user_id']
    response = pub.BaseResponse()
    # column_list = [x for x in models.Column.objects.values_list('id', "name")]

    if request.method == "POST":
        # 添加
        if oper_type == "add":
            print(request.POST)

            name = request.POST.get('name')
            select_id = request.POST.get('select_id')

            if not response.statusCode and not name.strip():
                response.statusCode = 300
                response.message = "角色名称不能为空"

            # 判断角色名称是否存在
            if not response.statusCode:
                roles_obj = get_db_obj().roles.find_one({"name": name})
                if roles_obj:
                    response.statusCode = 300
                    response.message = "角色名称已存在"

            if not response.statusCode:

                get_db_obj().roles.insert({
                    "_id": str(ObjectId()),
                    "name": name,
                    "rights_ids": select_id,
                    "create_user_id": user_id,
                    "create_date": datetime.now()
                })

                response.statusCode = 200
                response.message = "添加成功"

        # 修改
        elif oper_type == "update":
            name = request.POST.get('name')
            select_id = request.POST.get('select_id')
            print(select_id)
            if not response.statusCode and not name.strip():
                response.statusCode = 300
                response.message = "角色名称不能为空"

            # 判断角色名称是否存在
            if not response.statusCode:
                roles_obj = get_db_obj().roles.find_one({"name": name, "_id": {"$ne": o_id}})
                if roles_obj:
                    response.statusCode = 300
                    response.message = "角色名称已存在"

            if not response.statusCode:
                get_db_obj().roles.update(
                    {"_id": o_id},
                    {"$set": {
                        "name": name,
                        "rights_ids": select_id,
                    }}
                )

                response.statusCode = 200
                response.message = "修改成功"

        # 删除
        elif oper_type == "del":
            # 判断该角色下是否有用户
            user_obj = get_db_obj().user.find_one({"role_id": o_id})
            if user_obj:
                response.statusCode = 300
                response.message = "删除失败,该角色下还存在用户,请将用户转移后在进行该操作"
                response.callbackType = None
            else:
                get_db_obj().roles.remove({"_id": o_id})

                response.statusCode = 200
                response.message = "删除成功"
                response.callbackType = None

        return JsonResponse(response.__dict__)

    else:
        # 添加
        if oper_type == "add":
            request.session["rights_ids"] = ""
            return render(request, 'webadmin/roles/roles_management_modal_add.html', locals())

        # 修改
        elif oper_type == "update":
            roles_obj = get_db_obj().roles.find_one({"_id": o_id})
            request.session["rights_ids"] = roles_obj["rights_ids"]
            return render(request, 'webadmin/roles/roles_management_modal_update.html', locals())

        elif oper_type == "json_data":

            result_data = collections.OrderedDict()
            result_data = sort_rights_data("", result_data)
            print(result_data)

            # 角色拥有权限的id
            if "rights_ids" in request.session:
                rights_ids = request.session["rights_ids"].split(",")
            else:
                rights_ids = ""

            rights_html = create_rights_html(result_data, rights_ids)
            print(rights_html)

            return HttpResponse(json.dumps(rights_html))
